package xyz.comfyz.web.commons.security.provider.token.impl;

import org.springframework.util.StringUtils;
import xyz.comfyz.web.commons.security.model.TokenConfig;
import xyz.comfyz.web.commons.utils.WebContextUtil;

import javax.servlet.http.Cookie;

/**
 * @author :    comfy
 * @date :      2018-05-12 16:04:49
 * @since :     1.8
 * <p>
 * token写入器 写到cookie中
 */
public final class CookieTokenWriter {

    public void write(TokenConfig tokenConfig, String value, boolean enableLocalCookie) {
        setCookie(tokenConfig.getDomain(), tokenConfig.getExpiry(), tokenConfig.getPath(), tokenConfig.getName(), value, enableLocalCookie);
    }

    public void remove(TokenConfig tokenConfig, boolean enableLocalCookie) {
        setCookie(tokenConfig.getDomain(), 0, tokenConfig.getPath(), tokenConfig.getName(), "", enableLocalCookie);
    }

    private void setCookie(String domain, int expiry, String path, String name, String value, boolean enableLocalCookie) {
        final Cookie cookie = new Cookie(name, value);
        if (StringUtils.hasText(domain)) {
            if (enableLocalCookie)
                addLocalCookie(path, name, value, expiry);
            cookie.setDomain(domain);
        }
        cookie.setPath(path);
        cookie.setMaxAge(expiry);
        WebContextUtil.response().addCookie(cookie);
    }

    private void addLocalCookie(String path, String name, String value, int expiry) {
        final Cookie cookie = new Cookie(name, value);
        cookie.setPath(path);
        cookie.setMaxAge(expiry);
        WebContextUtil.response().addCookie(cookie);
    }

}
